<template>
  <div class="app-container-flex" v-show="showDialog && !detailInfo.visible">
    <div class="width100">
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :queryMoreJson="true"
          :filter-list="filterInfo.searchList"
          :clearType="clearType"
          :slipSelectRequest="slipSelectRequest"
          :filter-btn="filterInfo.searchBtn"
        >
        </NewPageFilter>
        <el-button @click="closeDetailList">计量器具检定</el-button>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-excel>
            <el-button @click="exportExcel()">导出excel </el-button>
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <GroupSelect
            @callback="groupSelect"
            @callbackVal="updateGroupSelections"
            :options="groupSelectInfo.options"
            v-model:selections="groupSelectInfo.selections"
          ></GroupSelect>
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <TableContainer
        v-if="groupFlag"
        class="groupFlag-container"
        :isGroupSearch="true"
        v-model:data="groupSelectInfo.data"
        :field-list="tableInfo.fieldList"
        :checkBox="false"
        :tabIndex="false"
        :pager="false"
        :treeProps="{ children: 'children', hasChildren: 'hasChildren' }"
        @exChange="exChange"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
        :span-method="arraySpanMethod"
        :row-class-name="tableRowClassName"
      >
        <template v-slot:col-orderNo="scope">
          {{ scope.row.orderNo }}
        </template>
      </TableContainer>
      <TableContainer
        v-else
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :checkBox="false"
        :tabIndex="true"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
      >
      </TableContainer>
    </div>
  </div>
  <SetPreference
    v-if="preferenceInfo.visible"
    v-model:visible="preferenceInfo.visible"
    :searchList="filterInfo.searchList"
    :fieldList="tableInfo.fieldList"
    :customizeUserVO="filterInfo.query.customizeUserVO"
    @callback="setPreferenceCallback"
  />

  <AdvancedSearch
    v-if="advancedSearchInfo.visible"
    v-model:visible="advancedSearchInfo.visible"
    :fieldList="tableInfo.fieldList"
    v-model:formData="advancedSearchInfo.data"
    @callback="advancedSearchCallback"
  />

  <asset-instruments-plan-detail
    v-if="detailInfo.visible"
    v-model:visible="detailInfo.visible"
    :id="detailInfo.id"
    @returnBack="returnDetail"
  />
</template>
<script setup>
import {
  instrumentsHistoryRecordCustomizeListAll,
  getInstrumentsHistoryRecordCustomizeGroups,
} from '@/api/asset.js'
import {
  getInstrumentsHistoryRecordCustomizeListPage,
  exportExcelInstrumentsHistoryRecord,
} from '@/api/asset.js'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import AssetInstrumentsPlanDetail from './detail'

const props = defineProps(['visible'])
const { proxy } = getCurrentInstance()
const clearType = ref(true)
const groupFlag = ref(false)
const slipSelectRequest = ref(true)
// 过滤相关配置
const groupSelectInfo = ref({
  options: [],
  selections: [],
  data: [],
})
const filterInfo = ref({
  sortArr: [],
  query: {
    groupMap: {},
    groups: [],
    sortString: '',
    queryMap: {
      isEntry: {
        asTbName: 'asset_instruments_plan',
        columnName: 'is_entry',
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 1,
      },
    },
    customizeUserVO: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      value: 'excel',
      type: 'slot',
    },
  ],
})

// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  data: [],
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '详情',
        event: showPlanDetail,
        show: proxy.$permission('assetInstrumentsPlan:detail'),
        ifRender: function (row) {
          return row.isEntry === 1
        },
      },
    ],
  },
})
const detailListInfo = ref({
  visible: false,
})
const preferenceInfo = ref({
  visible: false,
})
const detailInfo = ref({
  visible: false,
  id: {},
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    proxy.$emit('update:visible', val) // 更新父组件visible
  },
})
function returnDetail() {
  detailInfo.value.visible = false
  getList()
}
//展示计划明细
function showPlanDetail(row) {
  detailInfo.value.id = row.id
  detailInfo.value.visible = true
}
function closeDetailList() {
  proxy.$store.dispatch('app/toggleOpenFilter')
  showDialog.value = false
  proxy.$emit('callback')
}
function updateGroupSelections(arr) {
  filterInfo.value.query.groups = arr
  groupSelectInfo.value.selections = arr
  if (!arr.length) {
    filterInfo.value.query.groups = []
    filterInfo.value.query.groupMap = {}
    groupSelectInfo.value.data = []
    groupFlag.value = false
  }
}
function groupSelect(arr) {
  if (arr.length) {
    //点击分组
    groupFlag.value = true
    filterInfo.value.query.groups = arr
    groupSelectInfo.value.selections = arr
    getCustomizeGroupsList()
  } else {
    proxy.$message.warning({
      message: '请选择分组条件！',
      showClose: true,
      duration: 3000,
    })
  }
}
//导出excel
function exportExcel() {
  exportExcelInstrumentsHistoryRecord(filterInfo.value.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
async function getCustomizeGroupsList(len, param, expande) {
  //分组查询
  let params = {}
  if (len) {
    params = param
  } else {
    params = filterInfo.value.query
  }
  if (
    filterInfo.value.query.queryDtoList &&
    filterInfo.value.query.queryDtoList.length
  ) {
    params = proxy.$fn.deepClone(params)
    params.queryMap = {}
  }
  await getInstrumentsHistoryRecordCustomizeGroups(params).then(async (res) => {
    if (res && res.success) {
      let data = res.data
      let newData = []
      if (len) {
        await data.forEach((item, index) => {
          newData.push({
            ...item,
            id: index + Math.random(),
            isColspan: true,
            children: [{ ...item, id: index + Math.random(), isColspan: true }],
          })
        })
        expande.children = newData
      } else {
        await data.forEach((item, index) => {
          newData.push({
            ...item,
            id: index + Math.random(),
            isColspan: true,
            children: [{ id: index + Math.random(), isColspan: true }],
          })
        })
        groupSelectInfo.value.data = newData
      }
    }
  })
}
function exChange(data, expandedRows) {
  //展开分组
  if (expandedRows) {
    let len = data.nextGroups.length
    if (len) {
      let params = {
        ...filterInfo.value.query,
        groups: data.nextGroups,
        groupMap: { ...data.query },
        queryMap: { ...filterInfo.value.query.queryMap, ...data.query },
      }
      getCustomizeGroupsList(len, params, data)
    } else {
      let params = {
        ...filterInfo.value.query,
        groups: [],
        groupMap: {},
        queryMap: { ...filterInfo.value.query.queryMap, ...data.query },
      }
      instrumentsHistoryRecordCustomizeListAll(params).then(async (res) => {
        if (res && res.success) {
          let resData = res.data
          await resData.forEach((item, index) => {
            item.id = index + Math.random()
            item.isColspan = false
          })
          data.children = resData
        }
      })
    }
  } else {
    data.children = [{ id: Math.random(), isColspan: true }]
  }
}
function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  filterInfo.value.query.queryMap = {}
  filterInfo.value.query.queryDtoList = [...obj.queryDtoList]
  advancedSearchInfo.value.data = obj.data
  if ((await groupSelectInfo.value.selections.length) > 0) {
    await getCustomizeGroupsList()
  } else {
    groupSelectInfo.value.data = []
    await getList()
  }
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  clearType.value = !clearType.value
}
// 获取列表
async function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  if (groupSelectInfo.value.selections.length > 0) {
    getCustomizeGroupsList()
  } else {
    groupSelectInfo.value.data = []
    tableInfo.value.initCurpage = Math.random()
    tableInfo.value.refresh = Math.random()
  }
}
function showDetail(row) {
  row.id = row.orderId
  detailInfo.value.data = row
  detailInfo.value.visible = true
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'assetInstrumentsHistoryRecordVO-com.slip.spd.entity.vo.asset.AssetInstrumentsHistoryRecordVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      let tableFieldInfo = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail,
        true
      )
      tableInfo.value.fieldList = tableFieldInfo.fieldList
      groupSelectInfo.value.options = tableFieldInfo.groupOption
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.searchList = searchInfo.searchList
      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.value.api = getInstrumentsHistoryRecordCustomizeListPage
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
    filterInfo.value.sortArr = arr
    filterInfo.value.query.sortString = arr.toString()
    getList()
  }
}
function tableRowClassName(row) {
  if (row.row.nextGroups) {
    return 'bg-color-EBEEF5'
  } else {
    return ''
  }
}
function arraySpanMethod({ row, column, rowIndex, columnIndex }) {
  if (row.nextGroups) {
    if (columnIndex === 0) {
      return {
        rowspan: 1,
        colspan: tableInfo.value.fieldList.length,
      }
    }
  }
}

let obj = {
  assetName: {
    label: '资产名称',
    value: 'assetName',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  isMandatoryInspection: {
    label: '是否强检',
    value: 'isMandatoryInspection',
    componentType: 'select-model',
    code: 'yes_or_no',
    show: false,
    hidden: true,
  },
  useStatus: {
    label: '使用状态',
    value: 'useStatus',
    componentType: 'select-model',
    code: 'asset_font_status',
    show: false,
    hidden: true,
  },
  preVerificationDate: {
    label: '上次检定日期',
    value: 'preVerificationDate',
    componentType: 'date',
    show: false,
    hidden: true,
  },
  preVerificationPeriod: {
    label: '检定周期',
    value: 'preVerificationPeriod',
    componentType: 'number',
    show: true,
    hidden: true,
  },
  checkDatePlan: {
    label: '计划检定日期',
    value: 'checkDatePlan',
    componentType: 'date',
    show: false,
    hidden: true,
  },
  commonName: {
    label: '通用名称',
    value: 'commonName',
    componentType: 'input',
    show: false,
    hidden: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.value.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()
</script>

<style scoped></style>
